package com.qf.service.impl;

import com.qf.constant.CacheConstants;
import com.qf.constant.StrategyConstants;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import com.qf.service.FilterChainService;
import com.qf.util.PushMsgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Zwnan
 */
@Service("fee")
public class FeeFilterServiceImpl implements FilterChainService {

    @Autowired
    private CacheFeign cacheFeign;
    @Autowired
    private PushMsgUtil pushMsgUtil;

    @Override
    public boolean stratrgy(StandardSubmit submit) {

        //1.查询余额
        String key = CacheConstants.CACHE_PREFIX_CLIENT+submit.getClientID();
        Long fee = Long.parseLong(cacheFeign.hget(key,"fee"));
        //2.查询当前所需的费用
        Long feeMessage = submit.getFee();
        if (fee>=feeMessage){
           Long f =  cacheFeign.hincr(key,"fee",-feeMessage);
                if (f<0){
                    cacheFeign.hincr(key,"fee", feeMessage);
                    pushMsgUtil.sendLog(submit, StrategyConstants.STRATEGY_ERROR_FEE);
                    pushMsgUtil.pushReport(submit, StrategyConstants.STRATEGY_ERROR_FEE);
                    return false;
                }
        }else {
            cacheFeign.incr(key,feeMessage);
            return true;
        }
        //如果其他情况
        pushMsgUtil.sendLog(submit,StrategyConstants.STRATEGY_ERROR_FEE);
        pushMsgUtil.pushReport(submit,StrategyConstants.STRATEGY_ERROR_FEE);
        return false;
    }
}
